package com.ruoyi.develop.goodsSupplier.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import org.apache.poi.ss.usermodel.DateUtil;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.develop.goodsSupplier.mapper.GoodsSupplierMapper;
import com.ruoyi.develop.goodsSupplier.domain.GoodsSupplier;
import com.ruoyi.develop.goodsSupplier.service.IGoodsSupplierService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 供应商信息管理Service业务层处理
 *
 * @author qh
 * @date 2023-01-05
 */
@Service
public class GoodsSupplierServiceImpl implements IGoodsSupplierService {
    @Resource
    private GoodsSupplierMapper goodsSupplierMapper;

    @Value(value = "${ruoyi.path}")
    public String basePath;
    @Value(value = "${ruoyi.templatePath}")
    public String templatePath;
    @Value(value = "${ruoyi.templateImport}")
    public String templateImport;

    /**
     * 查询供应商信息管理
     *
     * @param id 供应商信息管理主键
     * @return 供应商信息管理
     */
    @Override
    public GoodsSupplier selectById(String id) {
        return goodsSupplierMapper.selectById(id);
    }

    /**
     * 查询供应商信息管理列表
     *
     * @param entity 供应商信息管理
     * @return 供应商信息管理
     */
    @Override
    public List<GoodsSupplier> selectList(GoodsSupplier entity) {
        return goodsSupplierMapper.selectList(entity);
    }

    /**
     * 新增供应商信息管理
     *
     * @param entity 供应商信息管理
     * @return 结果
     */
    @Override
    public int insert(GoodsSupplier entity) {
        if (StringUtils.isBlank(entity.getId())) {
            entity.setId(IdUtils.fastSimpleUUID());
        }
        String maxCode = goodsSupplierMapper.selectMaxCode();
        // 最大编号+1
        maxCode = Long.parseLong(maxCode)+1+"";
        entity.setCode(maxCode);
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(DateUtils.getNowDate());
        return goodsSupplierMapper.insert(entity);
    }

    @Override
    public String checkNameUnique(String name) {
        int count = goodsSupplierMapper.checkNameUnique(name);
        if (count > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 修改供应商信息管理
     *
     * @param entity 供应商信息管理
     * @return 结果
     */
    @Override
    public int update(GoodsSupplier entity) {
        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());
        return goodsSupplierMapper.update(entity);
    }

    /**
     * 批量删除供应商信息管理
     *
     * @param ids 需要删除的供应商信息管理主键
     * @return 结果
     */
    @Override
    public int deleteByIds(String[] ids) {
        return goodsSupplierMapper.deleteByIds(ids);
    }

    /**
     * 删除供应商信息管理信息
     *
     * @param id 供应商信息管理主键
     * @return 结果
     */
    @Override
    public int deleteById(String id) {
        return goodsSupplierMapper.deleteById(id);
    }

    @Override
    public List<SysDictData> selectAllSuppliers(GoodsSupplier param) {
        List<SysDictData> dictDatas = new ArrayList<>();
        List<GoodsSupplier> lists = selectList(param);
        lists.stream().forEach(entity -> {
            SysDictData dict = new SysDictData();
            dict.setDictLabel(entity.getName());
            dict.setDictValue(entity.getId());
            dict.setLabel(entity.getBankName());
            dict.setValue(entity.getBankNo());
            dictDatas.add(dict);
        });
        return dictDatas;
    }


    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Map<String, Object> importData(GoodsSupplier contact, MultipartFile file) {
        String tmplName = "goodsSupplier.xml";
        String errortext = "";
        Map<String, Object> map = new HashMap<>();
        int i = 0;
        int j = 0;
        try {
            // InputStream in = resource.getInputStream();
            InputStream in = new FileInputStream(basePath + File.separator
                    + templatePath + File.separator + templateImport + File.separator + tmplName);
            XLSReader mainReader = ReaderBuilder.buildFromXML(in);

            List<GoodsSupplier> list = new ArrayList<>();
            List<GoodsSupplier> list1 = new ArrayList<>();


            Map beans = new HashMap();
            beans.put("list", list);
            XLSReadStatus readStatus = mainReader.read(file.getInputStream(), beans);
            if (readStatus.isStatusOK()) {
                for (GoodsSupplier info : list) {
                    GoodsSupplier entity = new GoodsSupplier();
                    entity.setId(IdUtils.fastSimpleUUID());
                    BeanUtils.copyProperties(info, entity, "id");
                    if (StringUtils.isNotBlank(info.getIdx())) {
                        if (StringUtils.isNotBlank(info.getName())) {

                            if (StringUtils.isNotBlank(info.getFzDateStr())) {
                                try {
                                    Pattern pattern = Pattern.compile("[0-9]+[.]{0,1}[0-9]*[dD]{0,1}");
                                    Matcher isNum = pattern.matcher(info.getFzDateStr());
                                    if (!isNum.matches()) {
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                        entity.setFazhanDate(df.parse(info.getFzDateStr()));
                                    } else {
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                        String date = df.format(DateUtil.getJavaDate(Double.parseDouble(info.getFzDateStr())));
                                        entity.setFazhanDate(DateUtils.parseDate(date, "yyyy-MM-dd"));
                                    }
                                } catch (Exception e) {
                                    errortext += "序号为第" + info.getIdx() + "行数据，初次救助项目入机构时间格式错误，请规定的日期格式进行修改！";
                                    e.printStackTrace();
                                }
                            }

                            if (StringUtils.isNotBlank(errortext)) {
                                map.put("errorText", errortext);
                                map.put("num", i);
                                return map;

                            } else {
                                list1.add(entity);
                            }
                        }
                    } else {
                        errortext += "序号为" + info.getIdx() + "行数据，供应商名称不能为空，请填写后导入！";
                    }
                }
            }
            if (StringUtils.isBlank(errortext)) {
                for (GoodsSupplier info : list1) {
                    GoodsSupplier contact1 = new GoodsSupplier();
                    contact1.setName(info.getName());
                    List<GoodsSupplier> contactList = goodsSupplierMapper.selectList(contact1);
                    if (contactList.size() > 0) {
                        //info=contactList.get(0);
                        info.setId(contactList.get(0).getId());
                        j += this.update(info);
                    } else {
                        i += this.insert(info);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("errorText", errortext);
        map.put("num", i);
        map.put("numupdate", j);
        return map;
    }

    @Override
    public GoodsSupplier selectByName(String name) {
        return goodsSupplierMapper.selectByName(name);
    }
}
